//
//  NumSelector.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/11/8.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay


open class NumStepControl:JoView,UITextFieldDelegate{
    func updatePrice() {
        
        co_delay(delay: 0.01) {[weak self] in
            guard let `self` = self else {return}
            var t = self.numT.text ?? ""
            if t.hasSuffix("."){
                t = t.replacingFirst(matching: ".$", with: "")
                
            }
//            self.changePrice(t.CGFloatValue)
        }
    }
    
    
    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard var text = textField.text else {
            return true
        }
        if string == "-"{
            return false
        }

        if string.len < 1{
            updatePrice()
            return true
        }
        
        if range.location <= text.count{
            let index = text.index(text.startIndex, offsetBy: range.location)
            text.insert(contentsOf: string, at: index)
        }
        if text.hasSuffix("."){
            updatePrice()
            return true
        }
        if let _ = Regex("^\\d+(\\.\\d{1,4})?$").firstMatch(in: text){
            updatePrice()
            return true
        }
//        if let _ = Regex("\\d+\\.\\d{1,10}$").firstMatch(in: text){
//            updatePrice()
//            return true
//        }
        return false
       
    }
    weak var controller:UIViewController? = nil
    public var limit = NumLimit()
    public var value:Int = 1
    {
        didSet{
            numT.text = "\(value)"
        }
    }
    
    public var numT = JoTextField(id: "username", defaultV: nil, need: true, hiden: false, rule: JoRule(reg: EeLogin.phone, nil_msg: "请输入数量".loc, err_msg: "检查数量是否有效".loc))
    let addBt = UIButton()
    let reduceBt = UIButton()
    open override func addLayoutRules() {
        let numB = UIView()
        self.eelay = [
            [numB,[ee.X],[ee.T.B],45],
            [numT,[ee.X.Y],45],
            [reduceBt,[numT,ee.L,ee.R,-1],[ee.T.L.B],40],
            [addBt,[numT,ee.R,ee.L,1],[ee.T.L.B],40],
        ]
        numT.text = "1"
        numB.backgroundColor = .white
        numT.textAlignment = .center
        numT.keyboardType = .numberPad
        numT.backgroundColor = .white
        numT.delegate = self
        reduceBt.backgroundColor = .white
        addBt.backgroundColor = .white
        addBt.ui.bfont(size: 20).ncolor(hex: "#999").ntitle(title: "+")
        reduceBt.ui.bfont(size: 20).ncolor(hex: "#999").ntitle(title: "-")
        self.backgroundColor = UIColor(shex:"#aaa")
        self.bsui.set(radius: 0, width: 1, color: UIColor(shex:"#aaa"))
        
        _ = numT.ui.font13.cl_333.center
        numT.keyboardType = .numberPad
        numT.tintColor = UIColor.main_color
        addBt.tag = 1
        reduceBt.tag = -1
        
        addBt.addTarget(self, action: #selector(updateNum(sender:)), for: .touchUpInside)
        reduceBt.addTarget(self, action: #selector(updateNum(sender:)), for: .touchUpInside)
    }
    
    
    
    @objc open func updateNum(sender:UIButton) {
        _ = numT.resignFirstResponder()
        let num = sender.tag
        let newValue = self.value + num
        reduceBt.isEnabled = true
        addBt.isEnabled = true
        if newValue > (limit.max)
        {
            self.limit.maxMask.alert()
            addBt.isEnabled = false
        }
        if newValue < (limit.min)
        {
            reduceBt.isEnabled = false
            //            self.minAlert.alert()
        }
        if (newValue >= limit.min) && (newValue<=limit.max){
            self.value = newValue
        }
        
        //        self.willSetNewValue(newValue: newValue)
    }
    
    @discardableResult
    open func willSetNewValue(newValue:Int)->Bool {
        self.addBt.isEnabled = true
        self.reduceBt.isEnabled = true
        
        if newValue > (limit.max)
        {
            self.limit.maxMask.alert()
            self.addBt.isEnabled = false
            return false
        }
        if newValue < (limit.min)
        {
            reduceBt.isEnabled = false
            return false
        }
        self.value = newValue
        if newValue == limit.max
        {
            addBt.isEnabled = false
            
        }
        if newValue == limit.min
        {
            reduceBt.isEnabled = false
        }
        return true
    }
    
    open override var intrinsicContentSize: CGSize{
        return [127,30]
    }
    
}

open class NumPopSelector: CoInputController{
    public let stepCountrol = NumStepControl()
    public init() {
        super.init(nibName: nil, bundle: nil)
        self.modalPresentationStyle = .overFullScreen
    }
    
    public var limit = NumLimit()
    {
        didSet{
            stepCountrol.limit = limit
        }
    }
    
    
    
    public var value:Int = 1
    {
        didSet{
            stepCountrol.value = value
        }
    }
    
    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public var selectValue:(Int)->Void = {_ in}
    
    
    open func showAnimation() {
        weak var wself = self
        let previousTransform = self.cornerV.transform
        self.cornerV.layer.transform = CATransform3DMakeScale(0.8, 0.8, 0.0);
        self.cornerV.alpha = 0
        self.backView.alpha = 0
        
        UIView.animate(withDuration: 0.12, animations: { () -> Void in
            wself?.cornerV.alpha = 1
            wself?.backView.alpha = 1
            
            wself?.cornerV.layer.transform = CATransform3DMakeScale(1.005, 1.005, 0.0);
        }, completion: { (Bool) -> Void in
            UIView.animate(withDuration: 0.1, animations: { () -> Void in
                wself?.cornerV.layer.transform = CATransform3DMakeScale(0.99, 0.99, 0.0);
            }, completion: { (Bool) -> Void in
                UIView.animate(withDuration: 0.1, animations: { () -> Void in
                    wself?.cornerV.layer.transform = CATransform3DMakeScale(1.0, 1.0, 0.0);
                    //                    if self.animatedView != nil {
                    //                        self.animatedView!.animate()
                    //                    }
                }, completion: { (Bool) -> Void in
                    
                    wself?.cornerV.transform = previousTransform
                })
            })
        })
        
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        layoutView()
        backView.backgroundColor = UIColor(shex:"#00000044")
        self.inputBack.backgroundColor = .clear
        NotificationCenter.default.addObserver(self, selector: #selector(inputchange), name: UITextField.textDidEndEditingNotification,object:stepCountrol.numT)
        
    }
    
    open func disappear() {
        weak var wself = self
        //        let previousTransform = self.cornerV.transform
        self.cornerV.layer.transform = CATransform3DMakeScale(1, 1, 0.0);
        self.cornerV.alpha = 1
        self.backView.alpha = 1
        
        UIView.animate(withDuration: 0.20, animations: {
            wself?.cornerV.layer.transform = CATransform3DMakeScale(0.8, 0.8, 0.0);
            wself?.cornerV.alpha = 0
            wself?.backView.alpha = 0
        }) { (finsh) in
            wself?.dismiss(animated: false, completion: nil)
        }
    }
    
    @objc open func confirmNumValue() {
        let defaultV = "\(stepCountrol.value)"
        let newValue = Int("\(stepCountrol.numT.text ?? defaultV)") ?? stepCountrol.value
        let valid  = stepCountrol.willSetNewValue(newValue: newValue)
        if valid
        {
            self.selectValue(stepCountrol.value)
            self.disappear()
        }
    }
    
    @objc open func inputchange() {
        if let txt = stepCountrol.numT.text
        {
            //            var str = txt + string
            var str = txt
            let whitespace = CharacterSet.whitespacesAndNewlines
            var tempArray = str.components(separatedBy: whitespace)
            tempArray = tempArray.filter{
                $0 != ""
            }
            str = tempArray.joined(separator: "")
            if str.len > 0
            {
                if str.hasPrefix("0")
                {
                    JoAlertView(info: "提示".loc,"请输入有效的数字".loc,"确定".loc).show(at: self)
                    return
                }
                if str.len > 8
                {
                    JoAlertView(info: "提示".loc,"请输入有效的数字".loc,"确定".loc).show(at: self)
                    return
                }
                let newValue = Int(str) ?? stepCountrol.value
                stepCountrol.willSetNewValue(newValue: newValue)
            }
            else{
                stepCountrol.willSetNewValue(newValue: stepCountrol.value)
            }
        }
    }
    
    let confirmBt = UIButton()
    open func layoutView() {
        self.title = ""
        self.top_style = .transparent_light
        
        inputBack.eelay = [
            [cornerV,280,[ee.X.Y,[0,-30]]],
        ]
        stepCountrol.numT.delegate = self
        stepCountrol.controller = self
        cornerV.eelay = [
            [stepCountrol,[ee.X.T,[0,20]]],
            [confirmBt,[ee.X],[stepCountrol,ee.B,ee.T,30],[ee.B,-16]],
        ]
        confirmBt.ui.font(size: 13).ntitle(title: "确定".loc).ncolor(hex: UIColor.main_hex).set(radius: 2, width: 1, color: UIColor(shex:UIColor.main_hex))
        confirmBt.contentEdgeInsets = [5,16]
        cornerV.backgroundColor = .white
        confirmBt.addTarget(self, action: #selector(confirmNumValue), for: .touchUpInside)
    }
    
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.showAnimation()
    }
    
}

